/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.giant.bean.authentication;

import java.security.Principal;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 *
 * @author Harold
 */
@ManagedBean(name="loginBean2")
public class LoginBean2 {
	
	private String username;
	private String password;
	
	public LoginBean2(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		if(session != null){
			session.invalidate();
		}
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String login(){
		String navto = "";
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		FacesMessage msg = null;
                
                try {
			System.out.println("antes"+password+username);
			//Login via the Servlet Context
			request.login(username, password);
                        
			System.out.println("despues");
			//Retrieve the Principal
			Principal principal = request.getUserPrincipal();
			
			//Display a message based on the User role
			if(request.isUserInRole("ADMIN")){
				navto = "homePage";
			}else if(request.isUserInRole("USER")){
				navto = "manager";
			}
			
			//Add the welcome message to the faces context
			 msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Welcome", getUsername());
			return navto;
		} catch (ServletException e) {
			 msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
		}
		return "failure";
	}
	
	public void logout(){
            System.out.println("logout2");
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		if(session != null){
			session.invalidate();
		}
		FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(FacesContext.getCurrentInstance(), null, "/logintest.xhtml");
	}
	
}
